<template>
	<div>
		<Modal v-model="modals" width="850" scrollable footer-hide closable :title="titleFrom" :z-index="1"
			@on-cancel="handleReset" class-name="vertical-center-modal">
			<Form ref="formValidate" :model="formValidate" :label-width="110" :rules="ruleValidate"
				@submit.native.prevent>
				<Col v-bind="grid">
				<FormItem label="文件类型：">
					<Space direction="vertical" size="large">
						<RadioGroup v-model="fileType">
							<Radio label="1">文件</Radio>
							<Radio label="2">视频</Radio>
						</RadioGroup>
					</Space>
				</FormItem>
				</Col>
				<Col span="24">
					<FormItem label="标题：" prop="title">
						<Input
						    v-model="formValidate.title"
						    placeholder="请输入标题"
						    v-width="'50%'"
						/>
					</FormItem>
				</Col>
				<!-- 视频上传区域 -->
				<Col span="24" v-if="fileType === '2'">
					<FormItem label="上传视频：" prop="video_url">
						<Button @click="modalPicTap('video')">上传视频</Button>
						<div class="tips">建议时长：9～30秒，视频宽高比9:16（mp4格式）</div>
						<div class="iview-video-style" v-if="formValidate.video_url">
							<video class="video-style" :src="formValidate.video_url" controls="controls">
							</video>
							<div class="mark"></div>
							<!-- <Icon type="ios-trash-outline" class="iconv" @click="delVideo" /> -->
						</div>
					</FormItem>
				</Col>

				<!-- 文档上传区域 -->
				<Col span="24" v-if="fileType === '1'">
					<FormItem label="上传文档：" prop="document_url">
						<div class="upload-area">
							<Upload
								ref="upload"
								:before-upload="handleBeforeUpload"
								:on-success="handleSuccess"
								:on-error="handleError"
								:format="supportedFormats"
								:max-size="maxFileSize"
								:action="uploadUrl"
								:show-upload-list="false"
								:disabled="uploading"
								accept=".pdf,.doc,.docx,.txt,.ppt,.pptx,.xls,.xlsx"
							>
								<div class="upload-content" :class="{ 'uploading': uploading }">
									<Icon type="ios-cloud-upload-outline" size="32" />
									<p class="upload-text">{{ uploadText }}</p>
									<p class="upload-tip">支持 {{ supportedFormats.join(', ') }} 格式，最大 {{ maxFileSize / 1024 }}MB</p>
								</div>
							</Upload>
							
							<!-- 上传进度 -->
							<div v-if="uploading" class="upload-progress">
								<Progress :percent="uploadPercent" status="active" />
								<p class="progress-text">上传中... {{ uploadPercent }}%</p>
							</div>
						</div>

						<!-- 文件预览 -->
						<div v-if="selectedFile" class="file-preview">
							<div class="file-info">
								<Icon :type="getFileIcon(selectedFile.name)" size="24" />
								<div class="file-details">
									<p class="file-name">{{ selectedFile.name }}</p>
									<p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
								</div>
								<Button type="text" @click="removeFile" icon="ios-close-circle" class="remove-btn"></Button>
							</div>
							<div class="upload-action">
								<Button 
									type="primary" 
									:loading="uploading" 
									@click="handleDocumentSubmit"
									:disabled="!selectedFile"
								>
									{{ uploading ? '上传中...' : '开始上传' }}
								</Button>
								<Button style="margin-left: 8px" @click="removeFile">取消</Button>
							</div>
						</div>

						<!-- 上传结果 -->
						<div v-if="uploadResult" class="upload-result">
							<Alert type="success" show-icon>
								文档上传成功
								<template slot="desc">
									<p><strong>文件名称：</strong>{{ uploadResult.name }}</p>
									<p><strong>文件大小：</strong>{{ uploadResult.att_size }}</p>
									<p><strong>上传时间：</strong>{{ formatTime(uploadResult.created_at) }}</p>
									<p><strong>文件地址：</strong>
										<a :href="uploadResult.att_dir" target="_blank" v-if="uploadResult.att_dir">查看文件</a>
										<span v-else>暂无</span>
									</p>
								</template>
							</Alert>
							
							<div class="result-actions">
								<Button type="primary" @click="handleViewFile" v-if="uploadResult.att_dir">查看文件</Button>
								<Button style="margin-left: 8px" @click="handleUploadAnother">重新上传</Button>
							</div>
						</div>
					</FormItem>
				</Col>

				<div class="style-add">
					<Button class="mr14" type="default" @click="cancle">取消</Button>
					<Button type="primary" @click="handleSubmit('formValidate')">确认</Button>
				</div>
			</Form>
		</Modal>
		
		<Modal v-model="modalPic" width="960px" scrollable footer-hide closable title="上传商品图" :mask-closable="false"
			:z-index="1">
			<uploadPictures :isChoice="isChoice" @getPic="getPic" :gridBtn="gridBtn" :gridPic="gridPic" v-if="modalPic">
			</uploadPictures>
		</Modal>
	</div>
</template>

<script>
	import {
		brandCascader,
		productBrand,
		productBrandrev,
		createHelpCenter,
	} from "@/api/product";
	import {
		documentUploadApi
		
	} from "@/api/upload";
	import uploadPictures from "@/components/uploadPictures";
	
	export default {
		name: "menusFrom",
		components: {
			uploadPictures,
		},
		props: {
			formValidate: {
				type: Object,
				default: null,
			},
			fromName: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				// 文档上传相关
				supportedFormats: ['pdf', 'doc', 'docx', 'txt', 'ppt', 'pptx', 'xls', 'xlsx'],
				maxFileSize: 10240, // 10MB in KB
				uploadUrl: '/api/file/uploadDocument',
				uploading: false,
				uploadPercent: 0,
				selectedFile: null,
				uploadResult: null,
				
				ruleValidate: {
					title: [{
						required: true,
						message: '请输入标题',
						trigger: 'blur'
					}],
				},
				type: 1,
				modals: false,
				FromData: [],
				titleFrom: '',
				fileType: "1",
				fileData: {
					video_url: '',
				},
				gridBtn: {
					xl: 4,
					lg: 8,
					md: 8,
					sm: 8,
					xs: 8,
				},
				gridPic: {
					xl: 6,
					lg: 8,
					md: 12,
					sm: 12,
					xs: 12,
				},
				grid: {
					xl: 24,
					lg: 24,
					md: 12,
					sm: 24,
					xs: 24,
				},
				modalPic: false,
				typeTit: '',
				isChoice: "单选",
			}
		},
		computed: {
			uploadText() {
				if (this.uploading) return '文件上传中...'
				if (this.selectedFile) return '已选择文件，点击开始上传'
				return '点击或拖拽文件到此处上传'
			}
		},
		mounted() {
			this.getAddFrom()
			this.clearData()
		},
		methods: {
			clearData(){
				this.uploadResult = null
			},
			// 文档上传提交
			async handleDocumentSubmit() {
				if (!this.selectedFile) {
					this.$Message.error('请先选择文件')
					return
				}

				this.uploading = true
				this.uploadPercent = 0
				
				try {
					// 创建 FormData
					const formData = new FormData()
					formData.append('file', this.selectedFile)
					formData.append('file_type', '3') // 文档类型固定为3
					formData.append('module_type', '1') // 默认后台上传
					
					// 模拟上传进度
					this.simulateUploadProgress()
					
					// 调用上传接口
					const res = await documentUploadApi(formData)
					
					// 上传成功
					this.uploading = false
					this.uploadPercent = 100
					
					if (res.code === 0) {
						this.$Message.success(res.msg || '文档上传成功！')
						this.uploadResult = res.data
						
						// 将文档URL设置到表单中
						this.formValidate.document_url = res.data.att_dir
						this.$refs.formValidate.validateField('document_url')
						this.formValidate.fileType = this.fileType
						this.formValidate.url = res.data.att_dir
						this.formValidate.size = res.data.att_size
						this.formValidate.format = res.data.att_type
						// 发送成功事件给父组件
						this.$emit('on-document-upload-success', res.data)
					} else {
						this.$Message.error(res.msg || '上传失败')
					}
					
				} catch (error) {
					this.uploading = false
					console.error('上传失败:', error)
					
					if (error.msg) {
						this.$Message.error(error.msg)
					} else if (error.message) {
						this.$Message.error(error.message)
					} else {
						this.$Message.error('上传失败，请重试')
					}
				}
			},

			// 上传前校验
			handleBeforeUpload(file) {
				console.log('开始上传文档:', file.name)
				
				// 校验文件类型
				const fileFormat = file.name.split('.').pop().toLowerCase()
				if (!this.supportedFormats.includes(fileFormat)) {
					this.$Message.error(`不支持的文件格式：${fileFormat}，请上传文档文件！`)
					return false
				}
				
				// 校验文件大小 (10MB)
				const maxSizeBytes = this.maxFileSize * 1024
				if (file.size > maxSizeBytes) {
					this.$Message.error(`文件大小不能超过 ${this.maxFileSize / 1024}MB！`)
					return false
				}
				
				// 保存选中的文件
				this.selectedFile = file
				
				// 阻止自动上传，等待用户确认
				return false
			},
		
			// 上传成功处理（如果使用自动上传）
			handleSuccess(response, file, fileList) {
				console.log('上传成功:', response)
				this.uploading = false
				
				if (response.code === 0) {
					this.$Message.success(response.msg || '文档上传成功！')
					this.uploadResult = response.data
					this.formValidate.document_url = response.data.att_dir
					this.$emit('on-document-upload-success', response.data)
				} else {
					this.$Message.error(response.msg || '上传失败')
				}
			},
		
			// 上传失败处理
			handleError(error, file, fileList) {
				console.error('上传错误:', error)
				this.uploading = false
				this.$Message.error('文档上传失败，请重试！')
			},
			
			// 移除文件
			removeFile() {
				this.selectedFile = null
				this.uploadResult = null
				if (this.$refs.upload) {
					this.$refs.upload.clearFiles()
				}
				this.formValidate.document_url = ''
				this.formValidate.video_url = ''
			},
			
			// 查看文件
			handleViewFile() {
				if (this.uploadResult && this.uploadResult.satt_dir) {
					window.open(this.uploadResult.satt_dir, '_blank')
				}
			},
			
			// 重新上传
			handleUploadAnother() {
				this.removeFile()
			},

			// 获取文件图标
			getFileIcon(filename) {
				const ext = filename.split('.').pop().toLowerCase()
				const iconMap = {
					pdf: 'ios-document',
					doc: 'ios-document',
					docx: 'ios-document',
					txt: 'ios-document',
					ppt: 'ios-document',
					pptx: 'ios-document',
					xls: 'ios-document',
					xlsx: 'ios-document'
				}
				return iconMap[ext] || 'ios-document'
			},

			// 格式化文件大小
			formatFileSize(bytes) {
				if (bytes === 0) return '0 Bytes'
				const k = 1024
				const sizes = ['Bytes', 'KB', 'MB', 'GB']
				const i = Math.floor(Math.log(bytes) / Math.log(k))
				return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
			},

			// 格式化时间
			formatTime(timeString) {
				if (!timeString) return ''
				const date = new Date(timeString)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			},

			// 模拟上传进度
			simulateUploadProgress() {
				let progress = 0
				const interval = setInterval(() => {
					if (progress >= 90 || !this.uploading) {
						clearInterval(interval)
						return
					}
					progress += Math.random() * 10
					this.uploadPercent = Math.min(progress, 90)
				}, 200)
			},

			// 点击商品图
			modalPicTap(type) {
				this.typeTit = type;
				this.modalPic = true;
			},
			// delVideo(){
			//     let that = this;
			//     that.$set(that.formValidate, "video_url", "");
			//     this.$refs.formValidate.validateField('video_url');
			// },
			delVideo() {
			    // 先暂停视频并清理视频元素
			    const videoElement = this.$el.querySelector('.video-style');
			    if (videoElement) {
			        videoElement.pause();
			        videoElement.src = '';
			        videoElement.load();
			    }
			    
			    this.formValidate.video_url = "";
			    this.$nextTick(() => {
			        this.$refs.formValidate.validateField('video_url');
			    });
			},
			// 获取单张图片信息
			getPic(pc) {
				this.modalPic = false;
				if (this.typeTit == 'image') {
					this.formValidate.image = pc.att_dir;
					this.$refs.formValidate.validateField('image');
				} else {
					this.formValidate.video_url = pc.att_dir;
					this.$refs.formValidate.validateField('video_url');
				}
			},
			// 获取新增表单
			getAddFrom() {
				// brandCascader().then(async (res) => {
				// 		this.FromData = res.data;
				// 	})
				// 	.catch((res) => {
				// 		this.$Message.error(res.msg);
				// 	});
			},
			handleReset() {
				this.modals = false;
				// 重置文档上传状态
				this.removeFile();
				this.$parent.getData()
			},
			handleSubmit(name) {
				this.formValidate.pid = this.formValidate.fid[0]
				this.$refs[name].validate((valid) => {
					if (valid) {
						
						// 检查是否已上传文件
						if (this.fileType === '1' && !this.formValidate.document_url) {
							this.$Message.error('请先上传文档文件');
							return;
						} else if (this.fileType === '2' && !this.formValidate.video_url) {
							this.$Message.error('请先上传视频文件');
							return;
						}
						if(this.fileType == 2){
							this.formValidate.url = this.formValidate.video_url
							this.formValidate.format = "mp4"
						}
						if(this.formValidate.title == ""){
							this.$Message.error('请先填写标题');
							return;
						}
						 // 当文件类型为视频时，检查格式是否为 mp4
						if (this.fileType == 2) {
							// 检查视频格式是否为 mp4
						    if (!this.isMp4Format(this.formValidate.video_url)) {
						        this.$Message.error('视频格式必须是 MP4 格式');
						        return;
						    }
						                
						    this.formValidate.url = this.formValidate.video_url
						    this.formValidate.format = "mp4"
						}
						createHelpCenter(this.formValidate).then(res => {
							this.$Message.success(res.msg)
							
							this.modals = false
							this.uploadResult = null
							this.selectedFile = null
							setTimeout(() => {
								this.$emit("getList");
								this.clear();
							}, 600);
						}).catch(err => {
							this.$Message.error(err.msg)
						})
						
					} else {
						this.$Message.error('请输入标题');
					}
				})

			},
			// 添加一个新的方法来检查视频格式
			isMp4Format(videoUrl) {
			    if (!videoUrl) return false;
			    
			    // 方法1: 检查文件扩展名
			    const extension = videoUrl.split('.').pop().toLowerCase();
			    if (extension === 'mp4') {
			        return true;
			    }
			    
			    // 方法2: 检查URL中是否包含mp4关键字（更严格的检查）
			    const videoName = videoUrl.split('/').pop().toLowerCase();
			    return videoName.includes('.mp4') || extension === 'mp4';
			    
			    // 方法3: 如果需要更严格的验证，可以添加MIME类型检查
			    // 但注意：这需要实际文件信息，而不仅仅是URL
			},
			cancle() {
				this.modals = false
				this.formValidate.url = ""
				this.formValidate.format = ""
				this.formValidate.title = ""
				this.uploadResult = null
			}
		}
	};
</script>

<style scoped lang="stylus">
	.style-add {
		display: flex;
		justify-content: flex-end;
	}

	.mr14 {
		margin-right: 14px
	}

	/deep/.ivu-cascader-menu {
		height: auto;
		max-height 165px !important
	}

	/deep/.ivu-cascader-menu-item {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/deep/.ivu-select-item {
		max-width 294px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.trees-coadd {
		width: 100%;
		height: 500px;
		border-radius: 4px;
		overflow: hidden;
	}

	.scollhide {
		width: 100%;
		height: 100%;
		overflow: auto;
		margin-left: 18px;
		padding: 10px 0 10px 0;
		box-sizing: border-box;
	}

	.content {
		font-size: 12px;
	}

	.time {
		font-size: 12px;
		color: #2d8cf0;
	}

	.icons-item {
		float: left;
		margin: 6px 6px 6px 0;
		width: 53px;
		text-align: center;
		list-style: none;
		cursor: pointer;
		height: 50px;
		color: #5c6b77;
		transition: all 0.2s ease;
		position: relative;
		padding-top: 10px;
		font-size: 20px;
	}

	.search-rule {
		display: flex;
		align-items: center;
		padding: 10px;
		background-color: #f2f2f2;
	}

	.rule {
		display: flex;
		flex-wrap: wrap;
		max-height: 700px;
		overflow: scroll;
	}

	/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
	.rule::-webkit-scrollbar {
		width: 6px;
		height: 6px;
		background-color: #f5f5f5;
	}

	/*定义滚动条轨道 内阴影+圆角*/
	.rule::-webkit-scrollbar-track {
		border-radius: 4px;
		background-color: #f5f5f5;
	}

	/*定义滑块 内阴影+圆角*/
	.rule::-webkit-scrollbar-thumb {
		border-radius: 4px;
		background-color: #555;
	}

	.rule-list {
		background-color: #f2f2f2;
		width: 32%;
		margin: 5px;
		border-radius: 3px;
		padding: 10px;
		color: #333;
		cursor: pointer;
		transition: all 0.1s;
		overflow: hidden;
	}

	.rule-list:hover {
		background-color: #c5d1dd;
	}

	.rule-list div {
		white-space: nowrap;
	}

	.select-rule {
		background-color: #c5d1dd;
	}

	.add {
		display: flex;
		align-items: center;
	}
	.iview-video-style {
	    width: 40%;
	    height: 180px;
	    border-radius: 10px;
	    background-color: #707070;
	    margin-top: 10px;
	    position: relative;
	    overflow: hidden;
	    .video-style {
	        width: 100%;
	        height: 100% !important;
	        border-radius: 10px;
	    }
	    .iconv{
	        color: #fff;
	        line-height: 180px;
	        width: 50px;
	        height: 50px;
	        display: inherit;
	        font-size: 26px;
	        position: absolute;
	        top: -74px;
	        left: 50%;
	        margin-left: -25px;
	    }
	    .mark{
	        position: absolute;
	        width: 100%;
	        height: 30px;
	        top: 0;
	        background-color: rgba(0, 0, 0, 0.5);
	        text-align: center;
	    }
	}

	/* 文档上传样式 */
	.upload-area {
		border: 2px dashed #dcdee2;
		border-radius: 6px;
		padding: 20px;
		text-align: center;
		margin-bottom: 16px;
		transition: all 0.3s;
	}

	.upload-area:hover {
		border-color: #2d8cf0;
	}

	.upload-content {
		cursor: pointer;
		transition: all 0.3s;
	}

	.upload-content.uploading {
		cursor: not-allowed;
		opacity: 0.6;
	}

	.upload-text {
		font-size: 14px;
		color: #515a6e;
		margin: 12px 0 6px;
	}

	.upload-tip {
		font-size: 12px;
		color: #808695;
	}

	.upload-progress {
		margin-top: 16px;
	}

	.progress-text {
		font-size: 12px;
		color: #808695;
		margin-top: 6px;
	}

	.file-preview {
		border: 1px solid #e8eaec;
		border-radius: 4px;
		padding: 12px;
		margin-bottom: 16px;
		background-color: #f8f9fa;
	}

	.file-info {
		display: flex;
		align-items: center;
		gap: 12px;
		margin-bottom: 12px;
	}

	.file-details {
		flex: 1;
	}

	.file-name {
		font-weight: 500;
		margin-bottom: 4px;
		word-break: break-all;
	}

	.file-size {
		font-size: 12px;
		color: #808695;
	}

	.remove-btn {
		color: #ed4014;
		font-size: 18px;
	}

	.upload-action {
		text-align: center;
	}

	.upload-result {
		margin-top: 16px;
	}

	.result-actions {
		margin-top: 12px;
		text-align: center;
	}
</style>